# -*- coding: utf-8 -*-

import re
import tkinter as tk
import numpy as np
from tkinter import filedialog
from pathlib import Path


def readPEER(*varargin):
    """
    This program is used to read ground motion data from PEER database

    @author: yexiang yan
    """
    if varargin == ():
        root = tk.Tk()
        root.withdraw()
        root.call('wm', 'attributes', '.', '-topmost', True)
        file_path = filedialog.askopenfilename(multiple=False)
        p = Path(file_path)
        file_name = p.name
    else:
        filefolder = varargin[0]
        file_name = varargin[1]
        file_path = Path(filefolder, file_name)

    with open(file_path, 'r') as f:
        content = f.read().splitlines()

    time_histories = []
    for line in content[4:]:
        currentLine = list(map(float, line.split()))
        time_histories.extend(currentLine)

    NPTS_DT = re.findall(r'-?\d*\.?\d+e?-?\d*', content[3])
    npts = int(NPTS_DT[0])
    dt = float(NPTS_DT[1])

    RSNlist = re.findall(r'\d+', file_name)
    RSN = int(RSNlist[0])

    time = np.arange(0, npts * dt, dt)

    # PEER_GM = {'time':time,'time_histories':time_histories,'dt':dt,'npts':npts,'RSN':RSN}
    tsg = np.array(time_histories)
    return tsg, time, dt, npts, RSN


if __name__ == '__main__':
    readPEER()
